<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { debounce } from 'lodash-es'
import dayjs from 'dayjs'
import Conference from '@/api/modules/conference'
import Speech from '@/utils/speech'

const route = useRoute()
const speech = new Speech()

const notFoundMessage = ref('加载中...')

// 滚动等待栏
const waitList = ref<HTMLDivElement | null>(null)
let lastTime = 0
let stopDuration = 0
let scrollDirection = 1
function scrollAnimation(now: number) {
  const delta = now - lastTime
  const offset = delta / 20
  lastTime = now
  if (waitList.value && waitList.value.scrollHeight > waitList.value.clientHeight + 23) {
    // 滚动到顶部或底部时停顿3秒
    if (waitList.value.scrollTop === 0 || waitList.value.scrollTop >= waitList.value.scrollHeight - waitList.value.clientHeight - 1) {
      stopDuration += delta
      if (stopDuration >= 3000) {
        scrollDirection = -scrollDirection
        waitList.value.scrollTop += delta * scrollDirection
        stopDuration = 0
      }
    }
    // 滚动中
    else {
      waitList.value.scrollTop += offset * scrollDirection
    }
  }
  requestAnimationFrame(scrollAnimation)
}

requestAnimationFrame(scrollAnimation)

// 议题时长相关内容
const totalSeconds = ref()

const meeting = ref<MeetingApiTypes | null>(null)
// 当前进行中的会议信息
const currentSubject = ref<SubjectApiTypes.subjectItem | null>(null)
// 已完成的议题列表
const completedSubjectList = ref<SubjectApiTypes.subjectItem[]>([])
// 等待呼叫的议题列表
const waitingSubjectList = ref<SubjectApiTypes.subjectItem[]>([])

// 临时新增人员
const tempAddPerson = ref<SubjectApiTypes.Person[]>([])

// 筛选并更新议题列表
function updateSubjectList(clearTempAddPerson = true) {
  if (!meeting.value) {
    return
  }

  // 根据议题状态筛选
  completedSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 2)
  waitingSubjectList.value = meeting.value.subjectList.filter(subject => subject.status === 0)
  // 议题只取前三个，现在更改为全部显示
  // waitingSubjectList.value = waitingSubjectList.value.slice(0, 3)
  const currentSubjectIndex = meeting.value.subjectList.findIndex(subject => subject.status === 1)
  if (currentSubjectIndex !== -1) {
    currentSubject.value = meeting.value.subjectList[currentSubjectIndex]
  }
  else {
    currentSubject.value = null
  }

  if (clearTempAddPerson) {
    tempAddPerson.value = []
  }
}

const repullMeeting = debounce(() => {
  Conference.getDetail(route.params.id as string).then((res) => {
    meeting.value = res.data
    updateSubjectList()
  })
}, 1000)

// 使用localStorage中存的时长数据的函数
function judgeDuration() {
  const savedEndTime = localStorage.getItem(`countdownEndTime_${route.params.id}`)
  const formatSaveEndTime = dayjs(savedEndTime)
  console.log(route.params.id)

  if (formatSaveEndTime) {
    const endTime = dayjs(formatSaveEndTime)
    const remainingTime = endTime.diff(dayjs(), 'seconds') // 获取剩余秒数

    // 如果剩余时间大于 0，则继续倒计时
    if (remainingTime > 0) {
      totalSeconds.value = formatSaveEndTime
    }
    else {
    // 倒计时结束，执行相应的逻辑
      localStorage.removeItem(`countdownEndTime_${route.params.id}`)
    }
  }
}

updateSubjectList()
judgeDuration()

// websocket连接
const BASEURL = import.meta.env.VITE_APP_WS_BASEURL
let websocket: WebSocket | null = null
onMounted(() => {
  websocket = new WebSocket(`${BASEURL}${route.params.id}`)
  websocket.onmessage = (event) => {
    const msg = JSON.parse(event.data)
    if (msg.type === 'repullMeeting') { // 重新拉取会议信息
      repullMeeting()
    }
    else if (msg.type === 'addTempPersons') { // 临时新增人员
      const subjectId = msg.data.subjectId// 议题id
      const tempPersons = msg.data.tempPersons// 临时新增人员列表
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) { // 会议中存在该议题
        subject.personList.push(...tempPersons)
      }
      if (currentSubject.value?.id === subjectId) { // 如果是当前进行中的议题，则新增人员还需显示到新增列席处
        tempAddPerson.value.push(...tempPersons)
        // 播报人员信息
        let personMsg = '请'
        for (const person of tempPersons) {
          personMsg += `${person.name}，`
        }
        personMsg += '马上参会'
        speech.speak(personMsg)
      }
    }
    else if (msg.type === 'noSuchMeeting') { // 会议不存在
      meeting.value = null
    }
    else if (msg.type === 'meetingInfo') { // 会议信息
      meeting.value = msg.data
      updateSubjectList()
      // speech.speak('语音测试')
    }
    else if (msg.type === 'updateSubjectStatus') { // 开始议题
      const { subjectId, status } = msg.data
      const subject = meeting.value?.subjectList.find(subject => subject.id === subjectId)
      if (subject) {
        subject.status = status
      }
      updateSubjectList()
      if (status === 1) {
        // 播报议题信息
        const index = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
        // 增加倒计时逻辑
        if (subject?.durationtime) {
          const foramtTime = dayjs(`${dayjs().format('YYYY-MM-DD')}${subject.durationtime}`)
          const hours = foramtTime.hour()
          const minutes = foramtTime.minute()
          const seconds = foramtTime.second()
          totalSeconds.value = dayjs().add(hours * 3600 + minutes * 60 + seconds, 'second')
          console.log(totalSeconds.value)

          // 保存倒计时的结束时间到 localStorage（可以改为数据库保存）
          localStorage.setItem(`countdownEndTime_${route.params.id}`, totalSeconds.value.format('YYYY-MM-DD HH:mm:ss'))
        }
        if (index === -1) {
          console.error('议题不存在')
        }
        speech.speak(`请第${index! + 1}项议题的相关人员参会`)
      }
      else if (status === 2) {
        localStorage.removeItem(`countdownEndTime_${route.params.id}`)
      }
    }
    else if (msg.type === 'addSubject') { // 新增议题
      const subject = msg.data
      meeting.value?.subjectList.push(subject)
      updateSubjectList(false)
    }
    else if (msg.type === 'removeSubject') { // 移除议题
      const subjectId = msg.data
      const subjectIndex = meeting.value?.subjectList.findIndex(subject => subject.id === subjectId)
      if (subjectIndex !== undefined && subjectIndex !== -1) {
        meeting.value?.subjectList.splice(subjectIndex, 1)
      }
      updateSubjectList(false)
    }

    notFoundMessage.value = '找不到该会议信息'
  }
})
onUnmounted(() => {
  websocket?.close()
})
</script>

<!-- <template>
  <div class="sub-conference">
    <div v-if="meeting">
      <header>
        <h2>{{ meeting.name }}</h2>
      </header>
      <div class="container border">
        <main>
          <div class="left border-bottom border-right">
            <h3 class="border-bottom">
              正在进行
            </h3>
            <div class="meeting-name">
              {{ currentSubject?.name }}
            </div>
            <h3 class="border-top border-bottom">
              列席人员
            </h3>
            <div class="person-list">
              <div v-for="person in currentSubject?.personList" :key="person.id" class="item">
                <TextBlink>
                  {{ person.name }}
                </TextBlink>
              </div>
            </div>
          </div>
          <div class="right border-bottom">
            <h3 class="border-bottom">
              等待呼叫
            </h3>
            <div ref="waitList" class="wait-list">
              <div v-for="subject in waitingSubjectList" :key="subject.id" class="item meeting-name">
                {{ subject.name }}
              </div>
              <div class="bottom-gap">
                到底了
              </div>
            </div>
          </div>
        </main>
        <footer>
          <div class="left border-right">
            <span>新增列席</span>
          </div>
          <div class="content">
            <TextBlink v-for="person in tempAddPerson" :key="person.id">
              {{ `${person.name} ` }}
            </TextBlink>
          </div>
        </footer>
      </div>
    </div>
    <div v-else class="text-notfound">
      {{ notFoundMessage }}
    </div>
  </div>
</template> -->

<template>
  <div class="sub-conference">
    <div v-if="meeting">
      <header>
        <h2 class="title">
          {{ meeting.name }}
        </h2>
      </header>
      <div class="content">
        <div class="left">
          <!-- <img src="../../assets/images/background.png"> -->
          <div class="wrapper">
            <div class="wrapper-title">
              <h3><img src="../../assets/images/shijianchuo.png">正在进行</h3>
            </div>
            <div v-if="currentSubject" class="nowmeeting-name">
              <div class="marquee-container">
                <div class="marquee">
                  {{ currentSubject?.name }}
                </div>
              </div>
            </div>
            <div v-else class="nowmeeting-name">
              暂无正在进行议题
            </div>
          </div>
          <div class="wrapper">
            <div class="wrapper-title">
              <h3><img src="../../assets/images/user.png" alt="">列席人员</h3>
            </div>
            <div v-if="!currentSubject?.personList" class="personname">
              无
            </div>
            <div class="person-list">
              <div v-for="person, index in currentSubject?.personList" :key="person.id" class="personname">
                {{ person.name }}老师
                <span v-if="currentSubject && index < currentSubject?.personList.length - 1">、</span>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="wrapper">
            <div class="wrapper-title">
              <h3><img src="../../assets/images/shijianzhouqi.png" alt="">等待呼叫</h3>
            </div>
            <div v-for="(subject, index) in waitingSubjectList" :key="subject.id" class="wating">
              <div class="marquee-container">
                <div class="marquee">
                  （{{ index + 1 }}）{{ subject.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bottom">
        <div class="bottom1">
          <div class="wrapper">
            <div class="wrapper-title">
              <h3><img src="../../assets/images/user.png" alt="">新增列席</h3>
            </div>
          </div>

        <!-- <div class="bottom2">
          <div class="wrapper">
            <div class="waiting-list">
              <div v-for="person in tempAddPerson" :key="person.id" class="wating">
                列席人员：{{ `${person.name} ` }}
              </div>
            </div>
          </div>
        </div> -->
        <!-- <div class="wrapper">
          <div class="wrapper-title">
            <h3>新增列席</h3>
          </div>
          <div class="row-container">
            <div v-for="person in tempAddPerson" :key="person.id" class="person-item">
              列席人员：{{ person.name }}
            </div>
          </div>
        </div> -->
        </div>
        <div class="bottom2">
          <div class="wrapper">
            <div class="waiting-list">
              <div v-for="person in tempAddPerson" :key="person.id" class="wating">
                列席人员：{{ `${person.name} ` }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="time">
        <div class="title-time">
          距离下一项议题还有：
        </div>
        <div class="time1">
          <el-col :span="8">
            <el-countdown :value="totalSeconds" style="color: red;" />
          </el-col>
        </div>
      </div>
    </div>
    <div v-else class="text-notfound">
      {{ notFoundMessage }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.title {
  height: 11vh;
  font-size: 30px;
  color: white;
  font-weight: 400;
  background: #3d84ff;
}

.content {
  display: flex;
}

.left {
  flex-basis: 50%;
  width: 50%;
  //padding: 2%;

  img {
    width: 25px;
    height: 25px;
    margin-right: 5px;
    margin-top: -2px;
    vertical-align: middle;
  }

  .person-list {
    white-space: normal;
  }

  .personname {
    display: inline-block;
    margin: 5px;
    line-height: 35px;
    color: #d22933;
  }

  .marquee-container {
    display: flex;             // 启用 flex 布局
    justify-content: center;   // 水平居中
    align-items: center;
    font-weight: bold;
  }
}

.content .right {
  flex-basis: 50%;
  width: 50%;
  //padding: 2%;
  background-color: #f6f9fe;
  text-align: center;

  img {
    width: 25px;
    height: 25px;
    margin-right: 5px;
    margin-top: -2px;
    vertical-align: middle;
  }

  h3 {
    color: rgb(63 143 231);
    height: 45px;
    line-height: 50px;
    margin: 10px;
  }

  .nowmeeting-name {
    padding: 0 10px;
    background-color: #3b87ff;
    min-height: 50px;
    line-height: 50px;
    color: #fff;

    .marquee-container {
      // overflow: hidden;
      white-space: break-all;
    }

    // .marquee {
    //   display: inline-block;
    //   // padding-left: 30%;
    //   animation: marquee 35s linear infinite;
    // }

    // @keyframes marquee {
    //   0% {
    //     transform: translateX(0);
    //   }

    //   20% {
    //     transform: translateX(0);
    //   }

    //   100% {
    //     transform: translateX(-80%);
    //   }
    // }
  }

  p {
    display: inline;
    height: 50px;
    line-height: 50px;
    color: #0d0f10;
    font-weight: 700;
  }

  // h4 {
  //   margin: 0;
  //   height: 50px;
  //   line-height: 50px;
  //   color: #0d0f10;
  //   background-color: #fff;
  // }

  .wating {
    padding: 0 5px;
    min-height: 50px;
    line-height: 50px;
    color: #707173;
    background-color: #eff8ff;

    .marquee-container {
      // overflow: hidden;
      white-space: break-all;
    }

    // .marquee {
    //   display: inline-block;
    //   // padding-left: 30%;
    //   animation: marquee 35s linear infinite;
    // }

    // @keyframes marquee {
    //   0% {
    //     transform: translateX(0);
    //   }

    //   20% {
    //     transform: translateX(0);
    //   }

    //   100% {
    //     transform: translateX(-80%);
    //   }
    // }
  }

  .wating:nth-child(2n) {
    background-color: #fff;
  }
}

.border {
  border: 1px solid black;
}

.border-top {
  border-top: 1px solid black;
}

.border-left {
  border-left: 1px solid black;
}

.border-bottom {
  border-bottom: 1px solid black;
}

.border-right {
  border-right: 1px solid black;
}

.scroll-text {
  font-size: 30px;
  color: red;
}

header {
  text-align: center;

  h2 {
    font-size: 40px;
    color: red;
    font-weight: 400;
    margin: 0;
    padding: 20px 0;
  }
}

.container {
  width: 80%;
  margin: 0 auto;

  .meeting-name {
    font-size: 20px;
    padding: 14px;
  }

  main {
    display: flex;

    h3 {
      text-align: center;
      background-color: #00b0f0;
      margin: 0;
      padding: 20px 0;
      font-size: 21px;
    }

    .left {
      flex-basis: 50%;
      width: 50%;

      .person-list {
        padding: 20px;
        display: flex;
        flex-wrap: wrap;
        gap: 20px;

        .item {
          font-size: 18px;
        }
      }
    }

    .right {
      flex-basis: 50%;
      width: 50%;

      .wait-list {
        height: 329px;

        /* 6个议题的高度 - 1px */
        overflow: hidden;

        .item {
          border-bottom: 1px solid black;
        }

        .bottom-gap {
          height: 20px;
          line-height: 20px;
          font-size: 12px;
          color: #aaa;
          text-align: center;
        }
      }
    }
  }

  footer {
    display: flex;
    height: 100px;

    .left {
      padding: 0 20px;
      width: 200px;
      font-size: 18px;
      display: flex;
      align-items: center;
    }

    .content {
      padding: 20px;
      font-size: 18px;
    }
  }
}

.text-notfound {
  text-align: center;
  color: red;
  font-size: 40px;
}

.wrapper {
  display: flex;
  justify-content: space-between;
  gap: 5px;
  flex-direction: column;
  padding: 10px;

  div.wrapper-title {
    text-align: center;
    font-weight: bold;
    margin: 5px;
    background-color: #d9e8fc;
    padding: 2px;
    border-radius: 10px;
    color: #409eff;
  }
}

.bottom {
  display: flex;

  .bottom1 {
    flex-basis: 22%;
    width: 22%;
    //padding: 2%;
    background-color: #f6f9fe;
    text-align: center;

    img {
      width: 25px;
      height: 25px;
      margin-right: 5px;
      margin-top: -2px;
      vertical-align: middle;
    }

    .waiting-list {
      white-space: normal;
    }

    .wating {
      padding: 0 10px;
      // min-height: 50px;
      // line-height: 50px;
      color: #707173;
      background-color: #eff8ff;
      display: inline-block;

      .marquee-container {
        // overflow: hidden;
        white-space: break-all;
      }
      // .marquee {
      //   display: inline-block;
      //   // padding-left: 30%;
      //   animation: marquee 35s linear infinite;
      // }

      // @keyframes marquee {
      //   0% {
      //     transform: translateX(0);
      //   }

      //   20% {
      //     transform: translateX(0);
      //   }

      //   100% {
      //     transform: translateX(-80%);
      //   }
      // }
    }
  }

  .bottom2 {
    display: flex;
    align-items: center;
    flex-basis: 70%;
    width: 70%;
    //padding: 2%;
    background-color: #f6f9fe;
    text-align: center;

    .waiting-list {
      white-space: normal;
    }

    .wating {
      justify-content: flex-start; /* 水平靠左对齐 */
      align-items: center;         /* 垂直居中对齐 */
      padding: 0 10px;
      // min-height: 50px;
      // line-height: 50px;
      color: #707173;
      background-color: #eff8ff;
      display: inline-block;
    }

    .marquee-container {
      // overflow: hidden;
      white-space: break-all;
    }
  }
}

.time {
  display: flex;
  margin-top: 8px;
  font-weight: bold;

  .title-time {
    display: flex;
    align-items: center;
    margin-left: 32%;
    color: #409eff;
    text-align: center;
    font-size: 30px;
  }

  .time1 {
    display: flex;
    align-items: center;
    color: red;
    font-size: 40px;
  }

  .time2 {
    display: flex;
    align-items: center;
    color: #707173;
    font-size: 30px;
  }
}

::v-deep(.el-statistic__content) {
  font-size: 40px;
  color: red;
  font-weight: bold;
}
</style>
